﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Autofac;
using System.Web;

namespace FlowBasis.Web.Autofac
{
    public class HttpRequestServiceResolverProvider
    {
        private const string HttpContextKey = "__AutofacRequestContainer__";

        private IContainer rootContainer;

        public HttpRequestServiceResolverProvider(IContainer rootContainer)
        {
            this.rootContainer = rootContainer;
        }

        public LifetimeScopeResolver GetLifetimeScopeResolverForRequest()
        {
            var serviceResolver = HttpContext.Current.Items[HttpContextKey] as LifetimeScopeResolver;
            if (serviceResolver == null)
            {
                serviceResolver = new LifetimeScopeResolver(this.rootContainer.BeginLifetimeScope());
                HttpContext.Current.Items[HttpContextKey] = serviceResolver;
            }

            return serviceResolver;
        }

        public void DisposeLifetimeScopeResolverForRequest()
        {
            var serviceResolver = HttpContext.Current.Items[HttpContextKey] as LifetimeScopeResolver;
            if (serviceResolver != null)
            {
                serviceResolver.Dispose();
                HttpContext.Current.Items.Remove(HttpContextKey);
            }
        }
    }
}
